<!--
 * @description: 暖通 首页
 * @author: cuicui
 * @Date: 2023-11-23 11:53:14
 * @LastEditTime: 2023-11-23 13:45:28
 * @LastEditors: cuicui
-->
<template>
  <business-layout custom-title>
    <template slot='header'>
      <a-tabs v-model='activeKey' :type='conputedEditPermission ? "editable-card" : "card"' @edit='handleEditTab'
              hideAdd>
        <a-tab-pane v-for='pane in panes' :key='pane.key' :closable='pane.closable'>
            <span slot='tab'>
              <a-icon type='edit' v-if='conputedEditPermission' class='edit-tab-color'
                      @click.stop='handleEditTab(pane.id, "edit")' />
              {{ pane.pageName }}
            </span>
        </a-tab-pane>
        <div slot='tabBarExtraContent'>
          <a-tooltip>
            <template slot='title'>
              全屏
            </template>
            <a-button shape='circle' v-if='fullscreenFlag' type='fullscreen' @click='handleChangeFullscreen'
                      icon='fullscreen'
                      style='color: #000;' />
          </a-tooltip>

          <a-tooltip v-if='conputedEditPermission'>
            <template slot='title'>
              新增
            </template>
            <a-button shape='circle' @click='handleEditTab(null, "add")' icon='plus' style='margin-left: 10px' />
          </a-tooltip>

          <a-tooltip>
            <template slot='title'>
              刷新
            </template>
            <a-button shape='circle' @click='refreshData' icon='reload' style='margin-left: 10px' />
          </a-tooltip>
        </div>
      </a-tabs>
    </template>
    <div class='home-contaienr' ref='home-contaienr'>
      <div class='header-action'>
      </div>
      <div class='home-main'>
        <svg-container :svgStr='svgStr' :eventTags='eventTags' :fullscreenFlag='fullscreenFlag'
                       :targetData='configurationDiagramData' />
        <!--        <particles-bg />-->
      </div>
    </div>
    <create-view
      ref='createView'
      :visible='visible'
      :loading='confirmLoading'
      :model='viewModel'
      @design='handleDesignShow'
      @ok='handleOk'
      @cancel='handleCancel' />

    <design
      ref='desogmView'
      :moduleId='moduleId'
      :pageName='pageName'
      :planId='activeKey'
      :visable='designVisable'
      :loading='designLoading'
      @close='designVisable = false'
    />
  </business-layout>
</template>

<script>
import SvgContainer from '@/business-components/svg-container'
import ParticlesBg from '@/components/ParticlesBg/index.vue'
import CreateView from '@/business-components/create-view'
import { mapState } from 'vuex'
import Design from '@/business-components/design/index.vue'
import { WS_PIC_DATA, WS_SENDDATA, WS_SENDPIC } from '@/store/mutation-types'
import { findPageIdModuleId, create, update, remove } from '@/api/canvasApi.js'

const moduleId = '02'
const editMark = 'nuantongbianji'
export default {
  name: 'Home',
  mixins: [],
  components: { CreateView, ParticlesBg, SvgContainer, Design },
  props: {},
  watch: {
    activeKey(val) {
      const resTab = this.panes.find(item => item.id === val)
      if (resTab) {
        this.svgStr = resTab.svg ? resTab.svg.replace(/pointID="/g, 'pointid="').replace(/pointid="/g, 'pointid="pointID_') : ''
        this.eventTags = resTab.eventTags ? resTab.eventTags.split(',') : []
        this.pointList = resTab.idList ? resTab.idList.split(',') : []
        this.$store.dispatch(WS_SENDPIC, this.pointList.join(','))
      }
    }
  },
  computed: {
    ...mapState({
      token: state => state.user.token,
      configurationDiagramData: state => state.ws[WS_PIC_DATA],
      moduleList: state => state.dataDicInfo.modules,
      permissionList: state => [...new Set(state.user.info.permissionList.filter(item => item.type === 'I').map(item => item.permissionCode))],
      userType: state => state.user.info.userType
    }),
    HomeContainer() {
      return this.$refs['home-contaienr']
    },
    conputedEditPermission() {
      if (this.userType === '1') {
        return true
      }
      if (this.permissionList.includes(editMark)) {
        return true
      }
      return false
    }
  },
  data() {
    this.moduleId = moduleId
    return {
      confirmLoading: false,
      mdl: {},
      activeKey: '',
      svgStr: '',
      pageName: '',
      pointList: [],
      fullscreenFlag: true,
      designVisable: false,
      designLoading: false,
      panes: [],
      eventTags: [],
      viewModel: {},
      visible: false
    }
  },
  created() {
    this.findPageIdModuleId()
    //回调函数
  },
  methods: {
    refreshData() {
      this.activeKey = ''
      this.panes = []
      this.findPageIdModuleId()
    },
    handleEditTab(id, action) {
      if (action === 'add') {
        this.visible = true
        this.viewModel = null
      }
      if (action === 'remove') {
        this.removeTab(id)
      }
      if (action === 'edit') {
        this.visible = true
        const paneItem = this.panes.find(item => item.id === id)
        this.pageName = paneItem.title
        this.activeKey = id
        this.viewModel = {
          ...paneItem,
          pageName: paneItem.pageName
        }
      }
    },
    handleChangeFullscreen() {
      const { HomeContainer } = this
      if (this.fullscreenFlag) {
        HomeContainer.requestFullscreen()
      } else {
        document.exitFullscreen()
      }
    },
    findPageIdModuleId() {
      findPageIdModuleId({
        moduleId
      }).then((res) => {
        this.panes = res.map(item => {
          return {
            ...item,
            key: item.id,
            title: item.pageName
          }
        })
        if (this.panes && this.panes.length > 0 && !this.activeKey) {
          this.activeKey = this.panes[0].key
        }
      })
    },
    handleDesignShow() {
      this.handleCancel()
      const moduleDicObj = this.moduleList.find(item => item.code === moduleId)
      if (window.PROJECT_CONFIG.DESIGNER_OPEN_FUN === '0') {
        this.designVisable = true
      }
      if (window.PROJECT_CONFIG.DESIGNER_OPEN_FUN === '1') {
        const targetUrl = window.PROJECT_CONFIG.VUE_APP_DESIGN_PROJECT_URL + `?moduleId=${moduleId}&moduleDicId=${moduleDicObj.id}&planId=${this.activeKey}&token=${this.token}&pageName=${this.pageName}`
        window.open(targetUrl)
      }
    },
    handleOk() {
      const that = this
      this.$refs.createView.form.validateFields((errs, values) => {
        if (errs) {
          return
        }
        const { pageName, id, isHidden } = values
        if (id) {
          update({
            ...this.panes.find(item => item.id === id),
            pageName, id, isHidden
          }).then(res => {
            that.findPageIdModuleId()
            this.visible = false
            this.$refs.createView.form.resetFields()
            this.$message.success('更新成功!')
          })
        } else {
          create({
            moduleId: that.moduleId,
            pageName,
            id, isHidden
          }).then(() => {
            that.findPageIdModuleId()
            this.$refs.createView.form.resetFields()
            this.$message.success('新增成功!')
            this.visible = false
          })
        }
      })
    },
    handleCancel() {
      const form = this.$refs.createView.form
      form.resetFields() // 清理表单数据（可不做）
      this.visible = false
    },
    removeTab(targetKey) {
      const that = this
      this.$confirm({
        title: '警告',
        content: '当前操作不可逆、确认删除当前页面么？',
        onOk() {
          remove({ id: targetKey }).then((result) => {
            if (result) {
              that.findPageIdModuleId()
              // 删除tab为当前选中tab的话重置到第一个选项
              if (that.activeKey === targetKey) {
                that.activeKey = ''
              }
              that.$message.success('更新成功！')
            }
          })
        },
        onCancel() {
        }
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      // const { HomeContainer } = this
      document.addEventListener('fullscreenchange', (res) => {
        if (document.fullscreenElement) {
          this.fullscreenFlag = false
        } else {
          this.fullscreenFlag = true
        }
      })

      const that = this
      let fun = function(event) {
        if (event.data.success === 'close-drawer') {
          that.designVisable = false
          that.findPageIdModuleId()
        }
      }
      // 注册postmessage事件
      window.addEventListener('message', fun)
    })
  },
  updated() {
  },
  destroyed() {
  }
}
</script>
<style lang='less' scoped>
</style>
